#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System;
using System.Linq;
using AbstractClass.Collections.Generic;

namespace AbstractClass.Runtime.Caching
{
    /// <summary>
    /// Represents a Least Recently Used eviction policy.
    /// </summary>
    /// <typeparam name="TKey">The type of the key in the cache.</typeparam>
    [Serializable]
    public class LruEvictionPolicy<TKey> : IEvictionPolicy<TKey>
    {
        private readonly HashMap<TKey, DateTime> _ageStore = new HashMap<TKey, DateTime>();

        #region IEvictionPolicy<TKey> Members

        /// <summary>
        /// Returns the key associated with the evicted entry.
        /// </summary>
        /// <returns>The key associated with the evicted entry.</returns>
        public TKey GetVictimEntry()
        {
            return _ageStore.OrderBy(item => item.Value).First().Key;
        }

        /// <summary>
        /// Registers usage of the specified key in the internal usage data store of the policy.
        /// </summary>
        /// <param name="key">The key to register.</param>
        public void RegisterKey(TKey key)
        {
            if (!_ageStore.ContainsKey(key))
                _ageStore.Add(key, DateTime.Now);
            else
                _ageStore[key] = DateTime.Now;
        }

        /// <summary>
        /// Revokes the data associated with the specified key from the 
        /// internal usage data store of the policy.
        /// </summary>
        /// <param name="key">The key to revoke.</param>
        public void Revoke(TKey key)
        {
            _ageStore.Remove(key);
        }

        /// <summary>
        /// Renews the policy by clearing all key usage data.
        /// </summary>
        public void Renew()
        {
            _ageStore.Clear();
        }

        #endregion
    }
}